var util = require('../../libs/util.js');
var pathtool = require('../../libs/pathtool.js');
var moment = require('../../libs/moment.min.js');
moment.locale('zh-cn');
//获取应用实例
var app = getApp()
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    registerText: true,
    userInfo: {},
    delivery: false,
    auth_result: false,
    pathListHeight: 300,
    currentVehicleType: "1",
    vehicleType: { "0": '1', "1": '2', "2": '3', "3": '4', "4": '5'},
    isReturn:false,
    name: "",
    pathData: [{ name: '按此输入发货点', type: 'warehouse', address: '' }, { name: '按此输入收货点', type: 'shop', address: '' }],
    price: 0,
    distance: 0,
    duration: 0,
    restriction: false,
    driver_name: "",
    vehicle_plate: "点击安排送货车辆",
    postData: {
      delivery_date: moment().format('YYYY-MM-DD'),
      loading_time: moment().format('YYYY-MM-DD HH:mm'),
      vehicle: null,
      driver: null,
      warehouse: '',
      distance: '',
      duration: '',
      carrier:'',
      customer:''
    },
    delivery_date: moment().format('YYYY-MM-DD'),
    loading_time:moment().format('YYYY-MM-DD')+' 00:00',
    showVehicle:false,
    showPrice:false
  },
  onShareAppMessage: function () {
    return {
      title: app.appName,
      path: '/pages/index/index'
    }
  },
  bindInput: function (e) {
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);

    if (item == 'delivery_date'){
      if(app.globalData.delivery_date_before_today == 0 && moment(e.detail.value).diff(moment(), 'days') < 0){
        wx.showToast({
          title: "日期不能早于今日",
          image: '/images/wrong.png',
          duration: 2000
        });
        this.setData({
          'postData.delivery_date': moment().format('YYYY-MM-DD')
        })
      }else{
        this.setData({
          'postData.delivery_date': e.detail.value
        })
      }
    }
    if (item == 'loading_time') {
      if(app.globalData.delivery_date_before_today == 0 && moment(e.detail.value).diff(moment(), 'days') < 0){
        wx.showToast({
          title: "日期不能早于今日",
          image: '/images/wrong.png',
          duration: 2000
        });
        this.setData({
          'postData.loading_time': moment().format('YYYY-MM-DD HH:mm')
        })
      }else{
        this.setData({
          'postData.loading_time': moment(e.detail.value).format('YYYY-MM-DD HH:mm')
        })
      }
    }
  },
  onShow: function () {
    var that = this;
    wx.getStorage({
      key: 'path_vehicle',
      success: function (res) {
        console.log(res.data)
        if (res.data) {
          that.setData({
            driver_name: '主司机：' +  (res.data.name||'无')+'，副司机：' + (res.data.name2||'无'),
            vehicle_plate: '车辆：' + res.data.plate
          });
          var postData = that.data.postData;
          postData.vehicle = res.data.ID;
          postData.driver = res.data.driver;
          postData.driver2 = res.data.driver2||'';
          that.setData({
            postData: postData
          });
          wx.removeStorage({
            key: 'path_vehicle',
            success: function (res) {
            }
          });
        }
      }
    });
    wx.getStorage({
      key: 'path_carrier',
      success: function (res) {
        if (res.data) {
          that.setData({
            carrierName: res.data.name
          });
          var postData = that.data.postData;
          postData.carrier = res.data.carrier_coid;
          that.setData({
            postData: postData
          });
          wx.removeStorage({
            key: 'path_carrier',
            success: function (res) {
            }
          });
        }
      }
    }); 
    wx.getStorage({
      key: 'path_customer',
      success: function (res) {
        if (res.data) {
          that.setData({
            customerName: res.data.name
          });
          var postData = that.data.postData;
          postData.customer = res.data.value;
          that.setData({
            postData: postData
          });
          wx.removeStorage({
            key: 'path_customer',
            success: function (res) {
            }
          });
        }
      }
    });
    wx.getStorage({
      key: 'path_containeryard',
      success: function (res) {
        if (res.data) {
          that.setData({
            containeryardName: res.data.name
          });
          var postData = that.data.postData;
          postData.containeryard = res.data.value;
          that.setData({
            postData: postData
          });
          wx.removeStorage({
            key: 'path_containeryard',
            success: function (res) {
            }
          });
        }
      }
    });
    wx.getStorage({
      key: 'path_warehouse',
      success: function (res) {
        console.log(res)
        if (res.data) {
          var data = that.data.pathData;
          var loading_time = res.data.loading_time;
          var timepatt = new RegExp("^[0-9]{2}:[0-9]{2}");
          if (!timepatt.test(loading_time)) {
            loading_time =moment().format('YYYY-MM-DD')+' 00:00';
          };
          if(loading_time.length < 10 && loading_time.indexOf(":")> -1){
            loading_time =moment().format('YYYY-MM-DD')+' '+ loading_time;
          }
          data[res.data.index] = { name: res.data.name, type: 'warehouse', address: res.data.address, latitude: res.data.latitude, longitude: res.data.longitude, loading_time: loading_time,is_custom_distance:res.data.is_custom_distance, id: res.data.value };
          that.setData({
            pathData: data
          });
          var postData = that.data.postData;
          if(res.data.index == 0){
            postData.warehouse = res.data.value;
            postData.loading_time = loading_time;
          }
          var pathName = [];
          for (var i = 0; i < data.length;i++){
            pathName.push(data[i].name);
          }

          that.setData({
            postData: postData,
            pathName: pathName.join("-")
          });
          pathtool.calculateDistance(that, that.data.isReturn, that.data.pathData, false);
          wx.removeStorage({
            key: 'path_warehouse',
            success: function (res) {
            }
          });
        }
      }
    });
    wx.getStorage({
      key: 'path_shop',
      success: function (res) {
        console.log(res)
        if (res.data) {
          var data = that.data.pathData;
          var shop_time = res.data.receive_time;
          var timepatt = new RegExp("^[0-9]{2}:[0-9]{2}");
          if (!timepatt.test(shop_time)) {
            shop_time = '00:00';
          };
          data[res.data.index] = { name: res.data.name, type: 'shop', address: res.data.address, latitude: res.data.latitude, longitude: res.data.longitude, shop_time: shop_time, id: res.data.value };
          var pathName = [];
          for (var i = 0; i < data.length; i++) {
            pathName.push(data[i].name);
          }

          that.setData({
            pathData: data,
            pathName: pathName.join("-")
          });
          pathtool.calculateDistance(that, that.data.isReturn,that.data.pathData, false);
          wx.removeStorage({
            key: 'path_shop',
            success: function (res) {
            }
          });
        }
      }
    });
    wx.getStorage({
      key: 'path_historyAddress',
      success: function (res) {
        if (res.data) {
          var data = that.data.pathData;
          data[res.data.index].name = res.data.name;
          data[res.data.index].address = res.data.address;
          data[res.data.index].latitude = res.data.latitude;
          data[res.data.index].longitude = res.data.longitude;
          data[res.data.index].province = res.data.province;
          data[res.data.index].city = res.data.city;
          data[res.data.index].area = res.data.area;
          var pathName = [];
          for (var i = 0; i < data.length; i++) {
            pathName.push(data[i].name);
          }

          that.setData({
            pathData: data,
            pathName: pathName.join("-")
          });
          pathtool.calculateDistance(that, that.data.isReturn,that.data.pathData, false);
          wx.removeStorage({
            key: 'path_historyAddress',
            success: function (res) {
            }
          });
        }
      }
    });
    wx.getStorage({
      key: 'warehouseConfig',
      success: function (res) {
        if (res.data) {
          var data = that.data.pathData, postData = that.data.postData, index = res.data.index;
          if (res.data.alias) {
            data[index].name = res.data.alias;
          }
          data[index].shipper = res.data.shipper;
          data[index].shipper_phone = res.data.shipper_phone;
          postData.delivery_date = res.data.delivery_date;
          postData.loading_time = res.data.loading_time;
          that.setData({
            pathData: data,
            postData: postData
          });
          wx.removeStorage({
            key: 'warehouseConfig',
            success: function (res) {
            }
          });
        }
      }
    });
    wx.getStorage({
      key: 'shopConfig',
      success: function (res) {
        if (res.data) {
          var data = that.data.pathData, index = res.data.index;
          if (res.data.alias) {
            data[index].name = res.data.alias;
          }
          data[index].shop_time = res.data.receive_time;
          data[index].packages = res.data.package || 0;
          data[index].goodsInfo = res.data.goodsInfo||'';
          data[index].receiver = res.data.receiver;
          data[index].receiver_phone = res.data.receiver_phone;
          that.setData({
            pathData: data
          });
          wx.removeStorage({
            key: 'shopConfig',
            success: function (res) {
            }
          });
        }
      }
    });
    wx.getStorage({
      key: 'path_usually',
      success: function (res) {
        if (res.data) {
          console.log(res.data)
          var loading_time = res.data.loading_time;
          var timepatt = new RegExp("^[0-9]{2}:[0-9]{2}");
          if (!timepatt.test(loading_time)) {
            loading_time = moment().format('YYYY-MM-DD')+' 00:00:00';
          };
          var postData = {
            delivery_date: util.getDateStr(1),
            loading_time: loading_time,
            vehicle: res.data.vehicle,
            driver: res.data.driverId,
            warehouse: res.data.warehouse,
            price: res.data.price,
            onePrice_income: res.data.total_price,
            onePrice: res.data.onePrice,
            distance: res.data.mile,
            duration: res.data.duration,
            path_id: res.data.ID,
            path_name: res.data.name,
            customer: res.data.customer||'',
            customerName:res.data.customerName||'',
            isReturn: res.data.isReturn=='1'?true:false
          };
          that.setData({
            postData: postData,
            price: res.data.price || 0,
            onePrice: res.data.onePrice || 0,
            onePrice_income: res.data.total_price || 0,
            distance: res.data.mile || 0,
            duration: res.data.duration || 0,
            pathName: res.data.name,
            isReturn: res.data.isReturn == '1' ? true : false,
            customerName:res.data.customerName||''
          });
          if(res.data.plate){
            that.setData({
              vehicle_plate: '车辆：' + (res.data.plate || "")
            });
          }
          if(res.data.driver){
            that.setData({
              driver_name: '主司机：' +  (res.data.driver||'无')+'，副司机：' + (res.data.driver2||'无')
            });
          }
          util.getData("usuallyPathList", { path_id: res.data.ID }, function (res, error) {
            console.log(res)
            if (res.data.success) {
              console.log(res.data.data)
              var _data = res.data.data, _pathData = [];
              for (var i = 0; i < _data.length; i++) {
                var coord = String(_data[i].coord).split(",");
                if (_data[i].type == 'warehouse') {
                  var postData = that.data.postData;
                  postData.warehouse = _data[i].ID;
                  _pathData.push({ id: _data[i].ID, name: _data[i].name, type: _data[i].type, address: _data[i].address, loading_time: (_data[i].loading_time || moment().format('YYYY-MM-DD')+' 00:00'),latitude: coord[0], longitude: coord[1], is_custom_distance:_data[i].is_custom_distance });
                }else{
                  _pathData.push({ id: _data[i].ID, name: _data[i].name, type: _data[i].type, address: _data[i].address, receive_time: (_data[i].receive_time == 'undefined' ? '00:00' : _data[i].receive_time), latitude: coord[0], longitude: coord[1] });
                }
              };
              that.setData({
                pathData: _pathData
              });
              pathtool.calculateDistance(that, that.data.isReturn,that.data.pathData, false);
            }
          });
          wx.removeStorage({
            key: 'path_usually',
            success: function (res) {
            }
          });
        }
      }
    });
    wx.getStorage({
      key: 'path_map',
      success: function (res) {
        if (res.data) {
          that.setData({
            pathData: res.data
          });
          wx.removeStorage({
            key: 'path_map',
            success: function (res) {
            }
          });
        }
      }
    });
  },
  onReady: function (e) {
    this.mapCtx = wx.createMapContext('map');
  },
  onLoad: function (e) {

    var that = this;
    wx.setNavigationBarTitle({ "title": app.appName});
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          pathPageHeight: res.windowHeight - 120
        });
      }
    });
    if (app.globalData.user_id){
      that.setData({
        registerText: false
      });
    }
    //wx.vibrateLong();
    // wx.getSystemInfo({
    //   success: function(res) {
    //     console.log(res)
    //   }
    // })
    // wx.checkIsSupportSoterAuthentication({
    //     success(res) {
    //       if(res.supportMode[0] == 'fingerPrint'){
    //         wx.startSoterAuthentication({
    //           requestAuthModes: ['fingerPrint'],
    //           challenge: '123456',
    //           authContent: '请用指纹解锁',
    //           success(res) {
    //             console.log(res)
    //           }
    //         }) 
    //       }
    //         // res.supportMode = [] 不具备任何被SOTER支持的生物识别方式
    //         // res.supportMode = ['fingerPrint'] 只支持指纹识别
    //         // res.supportMode = ['fingerPrint', 'facial'] 支持指纹识别和人脸识别
    //     }
    // })

    // wx.openBluetoothAdapter({
    //   success: function (res) {
    //     wx.getBluetoothDevices({
    //       success: function (res) {
    //         console.log(res)
    //         var deviceId = res.devices[0].deviceId;
    //         wx.getBLEDeviceServices({
    //           // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
    //           deviceId: deviceId,
    //           success: function (res) {
    //             wx.getBLEDeviceCharacteristics({
    //               // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
    //               deviceId: deviceId,
    //               success: function (res) {
    //                 console.log('device getBLEDeviceCharacteristics:', res.characteristics)
    //               }
    //             })
    //           }
    //         })
    //       }
    //     })
    //   }
    // })
  },
  swithchChange: function (e) {
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  changeVehicleType: function (e) {
    var that = this;
    that.setData({
      currentVehicleType: e.detail.current
    })
    pathtool.calculateDistance(that, that.data.isReturn, that.data.pathData, false);
  },
  radioChange:function(e){
    console.log(e)
    var that = this;
    var deliveryMode = that.data.deliveryMode;
    for (var i = 0; i < deliveryMode.length; i++) {
      deliveryMode[i].checked = (deliveryMode[i].value == e.detail.value);
    };
    that.setData({
      deliveryMode: deliveryMode
    })
  },
  schedulePage: function (e) {
    var that = this;
    wx.redirectTo({
      url: '/pages/schedule/schedule'
    })
  },
  selectAddress: function (e) {
    var that = this;
    var pos = e.currentTarget.dataset.pos;
    var index = String(e.currentTarget.id).replace("path", "");
    //console.log(e);
    wx.chooseLocation({
      success: function (res) {
        //console.log(res)
        var address = res.address;
        var latitude = res.latitude;
        var longitude = res.longitude;
        var name = res.name;

        util.getData("/atapi/delivery/delivery/checkPointExists", {
          CO_ID:app.globalData.CO_ID,
          name: name,
          pos: pos
        }, function (res, error) {
          console.log(res); console.log(error)
          if (res.data.success) {
            var existsData = res.data.data;
            wx.showModal({
              title: '温馨提示',
              content: '名称为：“'+name+'”的'+(pos == 'warehouse'?'发货点':'收货点')+'已存在，是否直接调用？',
              success (res) {
                if (res.confirm) {
                  var pathData = that.data.pathData, _pathData = [],pathName = [];
                  for (var i = 0; i < pathData.length; i++) {
                    var n = pathData[i];
                    if (i == index) {
                      var coord = String(existsData.coord).split(',');
                      n.name = existsData.name;
                      n.address = existsData.address;
                      n.latitude = coord[0];
                      n.longitude = coord[1];
                      n.id = existsData.ID;
                      if(existsData.loading_time){
                        n.loading_time = existsData.loading_time;
                      }
                      if(existsData.shop_time){
                        n.shop_time = existsData.shop_time;
                      }
                    };
                    pathName.push(n.name)
                    _pathData.push(n);
                  }
                  that.setData({
                    pathData: _pathData,
                    pathName: pathName.join("-")
                  });
                  pathtool.calculateDistance(that, that.data.isReturn, that.data.pathData, false);
                }
              }
            })
          }else{
            util.getData("/xypapi/map/routerCalculate/geocode", {
              latitude: latitude,
              longitude: longitude
            }, function (geo, error) {
              console.log(geo); console.log(error)
              if (geo.data.success) {
                that.setData({
                  "addressComponent.province": geo.data.component.province,
                  "addressComponent.city": geo.data.component.city,
                  "addressComponent.area": geo.data.component.district
                });
              }
              var pathData = that.data.pathData, _pathData = [],pathName = [];
              for (var i = 0; i < pathData.length; i++) {
                var n = pathData[i], _name = name || address;
                if (i == index && _name) {
                  n.name = _name;
                  n.address = address;
                  n.latitude = latitude;
                  n.longitude = longitude;
                  n.province = geo.data.component.province;
                  n.city = geo.data.component.city;
                  n.area = geo.data.component.district;
                };
                pathName.push(n.name)
                _pathData.push(n);
              }
              that.setData({
                pathData: _pathData,
                pathName: pathName.join("-")
              });
    
              wx.getStorage({
                key: 'historyAddress',
                complete: function (res) {//console.log(res)
                  var data = res.data, _data = [];
                  if (res.errMsg == 'getStorage:ok') {
                    _data.push({ name: name, address: address, latitude: latitude, longitude: longitude, province: geo.data.component.province, city: geo.data.component.city, area: geo.data.component.district});
                    for (var i = 0; i < data.length; i++) {
                      if (i < 9) {
                        _data.push(data[i])
                      }
                    }
                  } else {
                    _data.push({ name: name, address: address, latitude: latitude, longitude: longitude, province: geo.data.component.province, city: geo.data.component.city, area: geo.data.component.district });
                  };
                  wx.setStorage({
                    key: "historyAddress",
                    data: _data
                  });
                }
              });
    
              pathtool.calculateDistance(that, that.data.isReturn, that.data.pathData, false);
            });
          }
        });
        
        
      }
    })
  },
  addAddress: function (e) {
    var that = this;
    console.log(e);
    var index = String(e.currentTarget.id).replace("path", "");
    var type = e.currentTarget.dataset.pos;
    var pathData = that.data.pathData;

    if (type == "warehouse") {
      wx.showActionSheet({
        itemList: ['增加一个发货点', '删除本发货点', '选择已注册发货点', '设置更多发货信息'],
        success: function (e) {
          //增加一个发货点
          if (e.tapIndex == 0) {
            var _pathData = [];
            for (var i = 0; i < pathData.length; i++) {
              var n = pathData[i];
              _pathData.push(n);
              if (i == index) {
                if (type == "warehouse") {
                  _pathData.push({ name: '按此输入发货点', type: 'warehouse', address: '' });
                }
              };
            }
            that.setData({
              pathData: _pathData
            });
            //删除本发货点
          } else if (e.tapIndex == 1) {
            var _pathData = [], warehouseNumber = 0;
            //检索是否只有一个发货点
            for (var i = 0; i < pathData.length; i++) {
              if (pathData[i].type == 'warehouse') {
                warehouseNumber++;
              };
            }
            if (warehouseNumber == 1) {
              wx.showToast({
                title: "须留1个发货点",
                image: '/images/wrong.png',
                duration: 2000
              });
              return false;
            }
            //找出并删除
            var pathName = [];
            for (var i = 0; i < pathData.length; i++) {
              var n = pathData[i];
              if (i != index) {
                _pathData.push(n);
                pathName.push(n.name);
              };
            }
            that.setData({
              pathData: _pathData,
              pathName: pathName.join("-")
            });
            pathtool.calculateDistance(that, that.data.isReturn,that.data.pathData, false);
            
            //选择已注册发货点
          } else if (e.tapIndex == 2) {
            wx.navigateTo({
              url: '/pages/index/warehouseList?index=' + index
            })
          } else if (e.tapIndex == 3) {
            if (!pathData[index].address) {
              wx.showToast({
                title: "请先规划路线",
                image: '/images/wrong.png',
                duration: 2000
              });
              return false;
            }
            wx.navigateTo({
              url: '/pages/index/warehouseConfig?index=' + index + '&delivery_date=' + pathData[index].delivery_date + '&loading_time=' + pathData[index].loading_time + '&depart_time=' + pathData[index].depart_time + '&shipper=' + pathData[index].shipper + '&shipper_phone=' + pathData[index].shipper_phone
            })
          }
        }
      })
      //_pathData.push({ name: '按此输入发货点', type: 'warehouse' });
    } else if (type == "shop") {
      wx.showActionSheet({
        itemList: ['增加一个收货点', '删除本收货点', '选择已注册收货点', '设置更多收货信息'],
        success: function (e) {
          //增加一个收货点
          if (e.tapIndex == 0) {
            var _pathData = [];
            for (var i = 0; i < pathData.length; i++) {
              var n = pathData[i];
              _pathData.push(n);
              if (i == index) { 
                if (type == "shop") {
                  _pathData.push({ name: '按此输入收货点', type: 'shop', address: '' });
                }
              };
            }
            that.setData({
              pathData: _pathData
            });
            //删除本收货点
          } else if (e.tapIndex == 1) {
            var _pathData = [], shopNumber = 0;
            //检索是否只有一个收货点
            for (var i = 0; i < pathData.length; i++) {
              if (pathData[i].type == 'shop') {
                shopNumber++;
              };
            }
            if (shopNumber == 1) {
              wx.showToast({
                title: "须留1个收货点",
                image: '/images/wrong.png',
                duration: 2000
              });
              return false;
            }
            //找出并删除
            var pathName = [];
            for (var i = 0; i < pathData.length; i++) {
              var n = pathData[i];
              if (i != index) {
                _pathData.push(n);
                pathName.push(n.name);
              };
            }
            that.setData({
              pathData: _pathData,
              pathName: pathName.join("-")
            });
            pathtool.calculateDistance(that, that.data.isReturn,that.data.pathData, true);
           
            //选择已注册收货点
          } else if (e.tapIndex == 2) {
            var warehouseSelect = [];
            for(var i=0;i<pathData.length;i++){
              if(pathData[i].type == 'warehouse' && pathData[i].id){
                warehouseSelect.push(pathData[i].id)
              }
            }
            console.log(warehouseSelect)
            if(warehouseSelect.length == 0){
              wx.showToast({
                title: "请先选择发货点",
                image: '/images/wrong.png',
                duration: 2000
              });
              return false;
            }
            wx.navigateTo({
              url: '/pages/index/shopList?warehouse='+warehouseSelect.join(',')+'&index=' + index
            })
          } else if (e.tapIndex == 3) {
            if (!pathData[index].address) {
              wx.showToast({
                title: "请先规划路线",
                image: '/images/wrong.png',
                duration: 2000
              });
              return false;
            }
            wx.navigateTo({
              url: '/pages/index/shopConfig?index=' + index + '&receive_time=' + pathData[index].receive_time + '&receiver=' + pathData[index].receiver + '&receiver_phone=' + pathData[index].receiver_phone
            })
          }
        }
      })
      //_pathData.push({ name: '按此输入收货点', type: 'shop' });
    }
  },
  selectVehicle: function () {
    wx.navigateTo({
      url: '/pages/index/pathSelectVehicle'
    })
  },
  selectCompany: function () {
    wx.navigateTo({
      url: '/pages/carrier/selectCarrier'
    })
  }, 
  selectCustomer: function() {
    wx.navigateTo({
      url: '/pages/index/customerList'
    })
  },
  selectContaineryard: function() {
    wx.navigateTo({
      url: '/pages/index/containeryardList'
    })
  },
  changeLoadingtime:function(e){
    var that = this;
      var loadingtime = e.currentTarget.dataset.loadingtime;
      that.setData({
        //currentId:e.currentTarget.dataset.id,
        datetime_picker:new Date(loadingtime).getTime(),
        datetime_picker_show:true
      })
  },
  datetimePicker:function(e){
    //console.log(moment(e.detail).format('YYYY-MM-DD HH:mm:ss'))
    var loading_time = moment(e.detail).format('YYYY-MM-DD HH:mm');
    if(app.globalData.delivery_date_before_today == 0 && moment(loading_time).diff(moment(), 'days') < 0){
      wx.showToast({
        title: "日期不能早于今日",
        image: '/images/wrong.png',
        duration: 2000
      });
      this.setData({
        loading_time:moment().format('YYYY-MM-DD') + ' ' + moment(e.detail).format('HH:mm')
      })
    }else{
      this.setData({
        loading_time:loading_time
      })
    }
  },
  datetimePickerCancel:function(){
    this.setData({
      datetime_picker_show:false
    })
  },
  datetimePickerConfirm:function(){
    var that = this;
    if(app.globalData.delivery_date_before_today == 0 && moment(that.data.loading_time).diff(moment(), 'days') < 0){
      wx.showToast({
        title: "日期不能早于今日",
        image: '/images/wrong.png',
        duration: 2000
      });
      that.setData({
        datetime_picker_show:false,
        "postData.loading_time":moment().format('YYYY-MM-DD') + ' ' + moment(that.data.loading_time).format('HH:mm')
      })
    }else{
      that.setData({
        datetime_picker_show:false,
        "postData.loading_time":that.data.loading_time
      })
    }
    
  },
  pathPriceDetail: function () {
    if (this.data.distance == 0) {
      wx.showToast({
        title: "请先规划路线",
        image: '/images/wrong.png',
        duration: 2000
      });
      return false;
    }
    wx.navigateTo({
      url: '/pages/index/pathPriceDetail?isReturn=' + this.data.isReturn + '&price=' + this.data.price + '&returnPrice=' + this.data.returnPrice + '&startPrice=' + this.data.startPrice + '&milePrice=' + this.data.milePrice + '&pointPrice=' + this.data.pointPrice + '&distance=' + this.data.distance + '&point=' + (this.data.pathData.length - 2)
    })
  },
  usuallyPath: function () {
    wx.redirectTo({
      url: '/pages/index/usuallyPath'
    })
  },
  isReturn:function(e){
    var that = this, postData = that.data.postData;
    postData.isReturn = !that.data.isReturn;
    that.setData({
      isReturn: !that.data.isReturn,
      postData: postData
    })
    if (that.data.distance > 0){
      pathtool.calculateDistance(that, that.data.isReturn, that.data.pathData, false);
    }
  },
  showMap:function(){
    if (this.data.distance == 0) {
      wx.showToast({
        title: "请先规划路线",
        image: '/images/wrong.png',
        duration: 2000
      });
      return false;
    };
    wx.setStorage({
      key: "path_map",
      data: this.data.pathData
    });
    wx.navigateTo({
      url: '/pages/index/map'
    })
  },
  submitDeliveryPath: function () {
    var that = this;
    wx.showLoading({
      title: '校验数据中...',
      mask: true
    });
    var postData = that.data.postData;
    var pathData = that.data.pathData;
    var _pathData = pathtool.checkPathPointList(that, pathData);//检查和修正路线途径点合法性
    if (_pathData.errMsg){
      wx.hideLoading();
      wx.showModal({
        title: '路线异常',
        content: _pathData.errText,
        success (res) {
          if (res.confirm) {
            
          }
        }
      })
      return false;
    }

    // pathtool.calculateDistance(that, that.data.isReturn,that.data.pathData, true,function(){
    //   if (postData.distance == '') {
    //     wx.showToast({
    //       title: "距离计算错误",
    //       image: '/images/wrong.png',
    //       duration: 3000
    //     });
    //     return false;
    //   }
      if (postData.delivery_date == '' || postData.delivery_date == undefined) {
        wx.showToast({
          title: "未配置发货时间",
          image: '/images/wrong.png',
          duration: 3000
        });
        return false;
      }
      for (var i = 0; i < pathData.length; i++) {
        pathData[i].sort = i + 1;
        pathData[i].CO_ID = app.globalData.CO_ID;
        if (pathData[i].type == 'warehouse'){
          pathData[i].loading_time = that.data.loading_time
          pathData[i].warehouse = pathData[i].id
        }else{
          pathData[i].shop = pathData[i].id
        }
        delete pathData[i].id
      }
      console.log(pathData)
      postData.isReturn = that.data.isReturn ? 1 : 0;
      postData.path_name = that.data.pathName;
      //postData.path = pathData;
      //postData.openid = app.globalData.openid;
      //postData.unionid = app.globalData.unionid;
      postData.CO_ID = app.globalData.CO_ID;
      //postData.user_id = app.globalData.user_id;
      //postData.user_name = app.globalData.truename;
      postData.customer = that.data.customer;
      postData.customerName = that.data.customerName;
      postData.goodsname = that.data.goodsname;
      postData.driverPrice = that.data.onePrice||0;
      postData.total_price = that.data.onePrice_income||0;
      postData.remark = that.data.remark;
      postData.create_mode = 'wxapp';
      if (postData.vehicle == null){
        postData.isPublish = 0;
      }else{
        postData.isPublish = 1;
      }
      console.log(postData);
      
      wx.hideLoading();
      setTimeout(function(){
        wx.hideLoading();
      },100)
      wx.showModal({
        title: '我要发货',
        content: '是否确认提交发货需求，提交后将自动通知司机等相关人员执行本路线服务。',
        success: function (res) {
          if (res.confirm) {
            wx.showLoading({
              title: '请稍候...',
            });
            util.postData("/sys/form/commonInsert",{
              "formId":"6E6999E1-1A6B-4F98-B1A4-A0A6BD77FAFC",
              "data":[postData],
              "condition":""
              }, function (res, error) {
              console.log(res); console.log(error)
              wx.hideLoading();
              setTimeout(function(){
                wx.hideLoading();
              },100)
              if (error) {
                wx.showToast({
                  title: res.data.data,
                  image: '/images/wrong.png',
                  duration: 3000
                });
                return false;
              }
              if (res.data.success) {
                wx.showToast({
                  title: "提交成功",
                  icon: 'success',
                  duration: 2000
                });
                let id = res.data.result[0]
                for (var i = 0; i < pathData.length; i++) {
                  pathData[i].delivery = id
                }
                util.postData("/sys/form/commonInsert",{
                  "formId":"1188A557-71F4-47EB-96C8-8AFE6E866C11",
                  "data":pathData,
                  "condition":""
                  }, function (res, error) {
                  })
              }
            });
          } else if (res.cancel) {
          }
        }
      })

    //});
    
    
    
  }
})
